<template>
  <div class="profile-container">
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <span>个人设置</span>
        </div>
      </template>
      
      <el-tabs v-model="activeTab">
        <el-tab-pane label="个人信息" name="info">
          <el-form 
            :model="userForm" 
            :rules="rules" 
            ref="userFormRef" 
            label-width="100px" 
            class="profile-form"
          >
            <el-form-item label="头像" prop="avatar">
              <el-upload
                class="avatar-uploader"
                action="/api/user/upload-avatar"
                :headers="uploadHeaders"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="userForm.avatar" :src="userForm.avatar" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
            
            <el-form-item label="用户名" prop="username">
              <el-input v-model="userForm.username" disabled />
            </el-form-item>
            
            <el-form-item label="公司名称" prop="companyName">
              <el-input v-model="userForm.companyName" />
            </el-form-item>
            
            <el-form-item label="联系人" prop="contactName">
              <el-input v-model="userForm.contactName" />
            </el-form-item>
            
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="userForm.phone" />
            </el-form-item>
            
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="userForm.email" />
            </el-form-item>
            
            <el-form-item label="公司地址" prop="address">
              <el-input v-model="userForm.address" type="textarea" :rows="2" />
            </el-form-item>
            
            <el-form-item label="营业执照" prop="businessLicense">
              <el-upload
                class="license-uploader"
                action="/api/user/upload-license"
                :headers="uploadHeaders"
                :limit="1"
                :on-success="handleLicenseSuccess"
                :on-exceed="handleExceed"
                :before-upload="beforeLicenseUpload"
              >
                <div v-if="userForm.businessLicense">
                  <el-image 
                    :src="userForm.businessLicense" 
                    fit="cover"
                    class="license-image"
                    :preview-src-list="[userForm.businessLicense]"
                  />
                </div>
                <el-button v-else type="primary">上传营业执照</el-button>
              </el-upload>
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="submitUserInfo">保存信息</el-button>
              <el-button @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <el-tab-pane label="修改密码" name="password">
          <el-form 
            :model="passwordForm" 
            :rules="passwordRules" 
            ref="passwordFormRef" 
            label-width="120px" 
            class="password-form"
          >
            <el-form-item label="原密码" prop="oldPassword">
              <el-input v-model="passwordForm.oldPassword" type="password" show-password />
            </el-form-item>
            
            <el-form-item label="新密码" prop="newPassword">
              <el-input v-model="passwordForm.newPassword" type="password" show-password />
            </el-form-item>
            
            <el-form-item label="确认新密码" prop="confirmPassword">
              <el-input v-model="passwordForm.confirmPassword" type="password" show-password />
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="changePassword">修改密码</el-button>
              <el-button @click="resetPasswordForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
<!--        <el-tab-pane label="配送设置" name="delivery">-->
<!--          <el-form-->
<!--            :model="deliveryForm"-->
<!--            ref="deliveryFormRef"-->
<!--            label-width="120px"-->
<!--            class="delivery-form"-->
<!--          >-->
<!--            <el-form-item label="默认物流公司" prop="defaultLogistics">-->
<!--              <el-select v-model="deliveryForm.defaultLogistics" placeholder="请选择默认物流公司">-->
<!--                <el-option-->
<!--                  v-for="item in logisticsCompanies"-->
<!--                  :key="item.value"-->
<!--                  :label="item.label"-->
<!--                  :value="item.value"-->
<!--                />-->
<!--              </el-select>-->
<!--            </el-form-item>-->

<!--            <el-form-item label="默认发货地址" prop="defaultShippingAddress">-->
<!--              <el-input v-model="deliveryForm.defaultShippingAddress" type="textarea" :rows="2" />-->
<!--            </el-form-item>-->

<!--            <el-form-item label="自动确认收货" prop="autoConfirmDays">-->
<!--              <el-input-number-->
<!--                v-model="deliveryForm.autoConfirmDays"-->
<!--                :min="3"-->
<!--                :max="30"-->
<!--              />-->
<!--              <span class="input-help">天后自动确认收货(3-30天)</span>-->
<!--            </el-form-item>-->

<!--            <el-form-item>-->
<!--              <el-button type="primary" @click="saveDeliverySettings">保存设置</el-button>-->
<!--              <el-button @click="resetDeliveryForm">重置</el-button>-->
<!--            </el-form-item>-->
<!--          </el-form>-->
<!--        </el-tab-pane>-->

<!--        <el-tab-pane label="消息通知" name="notification">-->
<!--          <el-form :model="notificationForm" label-width="120px" class="notification-form">-->
<!--            <el-form-item label="订单通知">-->
<!--              <el-switch v-model="notificationForm.orderNotification" />-->
<!--            </el-form-item>-->

<!--            <el-form-item label="物流通知">-->
<!--              <el-switch v-model="notificationForm.logisticsNotification" />-->
<!--            </el-form-item>-->

<!--            <el-form-item label="系统通知">-->
<!--              <el-switch v-model="notificationForm.systemNotification" />-->
<!--            </el-form-item>-->

<!--            <el-form-item label="短信通知">-->
<!--              <el-switch v-model="notificationForm.smsNotification" />-->
<!--            </el-form-item>-->

<!--            <el-form-item label="邮件通知">-->
<!--              <el-switch v-model="notificationForm.emailNotification" />-->
<!--            </el-form-item>-->

<!--            <el-form-item>-->
<!--              <el-button type="primary" @click="saveNotificationSettings">保存设置</el-button>-->
<!--            </el-form-item>-->
<!--          </el-form>-->
<!--        </el-tab-pane>-->
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { userAPI } from '@/api/api'

// 激活的标签页
const activeTab = ref('info')

// 用户表单数据
const userForm = reactive({
  avatar: '',
  username: '',
  companyName: '',
  contactName: '',
  phone: '',
  email: '',
  address: '',
  businessLicense: ''
})

// 密码表单数据
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 配送设置表单
const deliveryForm = reactive({
  defaultLogistics: '',
  defaultShippingAddress: '',
  autoConfirmDays: 7
})

// 物流公司选项
// const logisticsCompanies = [
//   { value: 'sf', label: '顺丰速运' },
//   { value: 'sto', label: '申通快递' },
//   { value: 'yto', label: '圆通速递' },
//   { value: 'zto', label: '中通快递' },
//   { value: 'yd', label: '韵达速递' },
//   { value: 'jd', label: '京东物流' },
//   { value: 'other', label: '其他' }
// ]

// 通知设置表单
const notificationForm = reactive({
  orderNotification: true,
  logisticsNotification: true,
  systemNotification: true,
  smsNotification: false,
  emailNotification: false
})

// 表单验证规则
const rules = {
  companyName: [
    { required: true, message: '请输入公司名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  contactName: [
    { required: true, message: '请输入联系人姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入公司地址', trigger: 'blur' }
  ]
}

// 密码验证规则
const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 表单引用
const userFormRef = ref(null)
const passwordFormRef = ref(null)
// const deliveryFormRef = ref(null)

// 获取上传头像所需的headers
const uploadHeaders = {
  Authorization: `Bearer ${localStorage.getItem('token') || ''}`
}

// 调试信息 - 打印token
const debugToken = () => {
  const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
  console.log('当前localStorage中的userInfo:', userInfo);
  console.log('token:', userInfo.token);
  
  // 也打印请求头中将使用的Authorization
  const headers = {};
  if (userInfo.token) {
    headers['Authorization'] = `Bearer ${userInfo.token}`;
  }
  console.log('将使用的请求头:', headers);
}

// 获取用户信息
const getUserInfo = async () => {
  // 打印调试信息
  debugToken();
  
  try {
    const response = await userAPI.getDealerInfo()
    if (response.code === 200) {
      const { data } = response
      userForm.avatar = data.avatar || ''
      userForm.username = data.username
      userForm.companyName = data.companyName
      userForm.contactName = data.contactName
      userForm.phone = data.phone
      userForm.email = data.email
      userForm.address = data.address
      userForm.businessLicense = data.businessLicense
    } else {
      ElMessage.error('获取用户信息失败')
    }
  } catch (error) {
    console.error('获取用户信息出错:', error)
    ElMessage.error('网络错误，请稍后重试')
  }
}

// 获取配送设置
const getDeliverySettings = async () => {
  try {
    const response = await userAPI.getDealerDeliverySettings()
    if (response.code === 200) {
      const { data } = response
      deliveryForm.defaultLogistics = data.defaultLogistics
      deliveryForm.defaultShippingAddress = data.defaultShippingAddress
      deliveryForm.autoConfirmDays = data.autoConfirmDays
    }
  } catch (error) {
    console.error('获取配送设置出错:', error)
  }
}

// 获取通知设置
const getNotificationSettings = async () => {
  try {
    const response = await userAPI.getNotificationSettings()
    if (response.code === 200) {
      const { data } = response
      notificationForm.orderNotification = data.orderNotification
      notificationForm.logisticsNotification = data.logisticsNotification
      notificationForm.systemNotification = data.systemNotification
      notificationForm.smsNotification = data.smsNotification
      notificationForm.emailNotification = data.emailNotification
    }
  } catch (error) {
    console.error('获取通知设置出错:', error)
  }
}

// 提交用户信息
const submitUserInfo = async () => {
  if (!userFormRef.value) return
  
  await userFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const response = await userAPI.updateDealerInfo(userForm)
        if (response.code === 200) {
          ElMessage.success('个人信息更新成功')
        } else {
          ElMessage.error(response.message || '个人信息更新失败')
        }
      } catch (error) {
        console.error('更新用户信息出错:', error)
        ElMessage.error('网络错误，请稍后重试')
      }
    } else {
      return false
    }
  })
}

// 修改密码
const changePassword = async () => {
  if (!passwordFormRef.value) return
  
  await passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const response = await userAPI.changePassword(passwordForm)
        if (response.code === 200) {
          ElMessage.success('密码修改成功')
          resetPasswordForm()
        } else {
          ElMessage.error(response.message || '密码修改失败')
        }
      } catch (error) {
        console.error('修改密码出错:', error)
        ElMessage.error('网络错误，请稍后重试')
      }
    } else {
      return false
    }
  })
}

// 保存配送设置
// const saveDeliverySettings = async () => {
//   try {
//     const response = await userAPI.updateDealerDeliverySettings(deliveryForm)
//     if (response.code === 200) {
//       ElMessage.success('配送设置已保存')
//     } else {
//       ElMessage.error(response.message || '保存配送设置失败')
//     }
//   } catch (error) {
//     console.error('保存配送设置出错:', error)
//     ElMessage.error('网络错误，请稍后重试')
//   }
// }

// 保存通知设置
// const saveNotificationSettings = async () => {
//   try {
//     const response = await userAPI.updateNotificationSettings(notificationForm)
//     if (response.code === 200) {
//       ElMessage.success('通知设置已保存')
//     } else {
//       ElMessage.error(response.message || '保存通知设置失败')
//     }
//   } catch (error) {
//     console.error('保存通知设置出错:', error)
//     ElMessage.error('网络错误，请稍后重试')
//   }
// }

// 头像上传前的校验
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg'
  const isPNG = file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG && !isPNG) {
    ElMessage.error('上传头像图片只能是 JPG 或 PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 营业执照上传前的校验
const beforeLicenseUpload = (file) => {
  const isJPG = file.type === 'image/jpeg'
  const isPNG = file.type === 'image/png'
  const isPDF = file.type === 'application/pdf'
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isJPG && !isPNG && !isPDF) {
    ElMessage.error('上传营业执照只能是 JPG、PNG 或 PDF 格式!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('上传营业执照大小不能超过 5MB!')
    return false
  }
  return true
}

// 头像上传成功的回调
// eslint-disable-next-line no-unused-vars
const handleAvatarSuccess = (response, _file) => {
  if (response.code === 200) {
    userForm.avatar = response.data.url
    ElMessage.success('头像上传成功')
  } else {
    ElMessage.error(response.message || '头像上传失败')
  }
}

// 营业执照上传成功的回调
// eslint-disable-next-line no-unused-vars
const handleLicenseSuccess = (response, _file) => {
  if (response.code === 200) {
    userForm.businessLicense = response.data.url
    ElMessage.success('营业执照上传成功')
  } else {
    ElMessage.error(response.message || '营业执照上传失败')
  }
}

// 文件超出限制的回调
// eslint-disable-next-line no-unused-vars
const handleExceed = (_files, _uploadFiles) => {
  ElMessage.warning('最多只能上传1个文件')
}

// 重置表单
const resetForm = () => {
  userFormRef.value?.resetFields()
  getUserInfo()
}

// 重置密码表单
const resetPasswordForm = () => {
  passwordFormRef.value?.resetFields()
}

// 重置配送设置表单
// const resetDeliveryForm = () => {
//   deliveryFormRef.value?.resetFields()
//   getDeliverySettings()
// }

// 组件挂载时获取用户信息和设置
onMounted(() => {
  getUserInfo()
  getDeliverySettings()
  getNotificationSettings()
})
</script>

<style scoped>
.profile-container {
  padding: 20px;
}

.profile-card {
  max-width: 900px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.profile-form, .password-form, .delivery-form, .notification-form {
  max-width: 600px;
  margin: 20px auto;
}

.avatar-uploader {
  text-align: center;
  margin-bottom: 20px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
  object-fit: cover;
  border-radius: 50%;
}

.license-image {
  width: 240px;
  height: 160px;
  object-fit: cover;
  border-radius: 4px;
  margin-bottom: 10px;
}

.input-help {
  margin-left: 10px;
  color: #999;
  font-size: 13px;
}
</style> 